package com.bsy.network.adapter

import com.bsy.framework.ext.data
import com.bsy.framework.utils.CommUtils.containsChinese
import com.bsy.network.error.ApiException
import com.bsy.network.response.BaseResponse
import com.google.gson.Gson
import okhttp3.ResponseBody
import retrofit2.Converter
import java.io.IOException
import java.lang.reflect.Type


/**
 * Created by Sincerity on 2022/8/10.
 * Copyright
 * 描述：
 */
class GsonResponseBodyConverter<T>(gson: Gson, type: Type) : Converter<ResponseBody, T?> {
    private val gson: Gson
    private val type: Type

    init {
        this.gson = gson
        this.type = type
    }


    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T? {
        val response: String = value.string()
        value.use {
            // 这里的type实际类型是 HttpResult<PhoneBean>  PhoneBean就是retData要获取的对象。
            val result = gson.fromJson<BaseResponse<T?>>(response, BaseResponse::class.java)

            val code: Int = result.code
            if (code == 0 || code == 200) {
                return gson.fromJson<T?>(response, type)
            } else {
                val resultError = gson.fromJson<BaseResponse<String>>(response, BaseResponse::class.java)
                //判断msg是否包含中文  因为后台乱搞 msg 和 data 均返回错误信息
                val msg = if (containsChinese(resultError.msg)) resultError.msg else resultError.msg
                //单独处理部分接口错误信息从Data返回
                if (resultError.code == 210) {
                    throw ApiException(resultError.code, msg.data())
                }
                throw ApiException(resultError.code, resultError.msg)
            }
        }
    }


}